<script setup lang="ts">
import Motion from "./utils/motion";
import { useRouter } from "vue-router";
import { message } from "@/utils/message";
import { loginRules } from "./utils/rule";
import TypeIt from "@/components/ReTypeit";
import { debounce } from "@pureadmin/utils";
import { useNav } from "@/layout/hooks/useNav";
import { useEventListener } from "@vueuse/core";
import type { FormInstance } from "element-plus";
import { operates, thirdParty } from "./utils/enums";
import { useLayout } from "@/layout/hooks/useLayout";
import LoginPhone from "./components/LoginPhone.vue";
import LoginRegist from "./components/LoginRegist.vue";
import LoginUpdate from "./components/LoginUpdate.vue";
import LoginQrCode from "./components/LoginQrCode.vue";
import { useUserStoreHook } from "@/store/modules/user";
import { initRouter, getTopMenu } from "@/router/utils";
import { bg, avatar, illustration } from "./utils/static";
import { ref, toRaw, reactive, watch, computed } from "vue";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import { IconifyIconOnline, IconifyIconOffline } from "@/components/ReIcon";
import { useDataThemeChange } from "@/layout/hooks/useDataThemeChange";
import type { PartialAuthData, LoginSuccessData } from "@/api/user";

import dayIcon from "@/assets/svg/day.svg?component";
import darkIcon from "@/assets/svg/dark.svg?component";
import Lock from "~icons/ri/lock-fill";
import User from "~icons/ri/user-3-fill";

defineOptions({ name: "Login" });

const router = useRouter();
const userStore = useUserStoreHook();
const loginDay = ref(7);
const loading = ref(false);
const checked = ref(false);
const disabled = ref(false);
const ruleFormRef = ref<FormInstance>();
const currentPage = computed(() => userStore.currentPage);
const partialAction = computed(() => userStore.partialAction);

const { initStorage } = useLayout();
initStorage();
const { dataTheme, overallStyle, dataThemeChange } = useDataThemeChange();
dataThemeChange(overallStyle.value);
const { title } = useNav();

const ruleForm = reactive({
  phone: "",
  password: "123456@Aa"
});

const rememberTip = "选择后将在此设备保留登录状态，公共设备请勿勾选。";

const onLogin = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(async valid => {
    if (!valid) return;
    loading.value = true;
    try {
      const res = await userStore.loginByUsername({
        phone: ruleForm.phone,
        password: ruleForm.password
      });
      if (res.success && res.data) {
        const data = res.data as PartialAuthData | LoginSuccessData;
        if ((data as PartialAuthData).partial) {
          // 部分登录场景交由路由监听处理，不提示弹窗
        } else {
          await initRouter();
          disabled.value = true;
          try {
            await router.push(getTopMenu(true).path);
            message("登录成功", { type: "success" });
          } finally {
            disabled.value = false;
          }
        }
      } else {
        message(res.msg || "登录失败", { type: "error" });
      }
    } catch (error: any) {
      message(error?.message ?? "登录失败", { type: "error" });
    } finally {
      loading.value = false;
    }
  });
};

const immediateDebounce: any = debounce(
  formRef => onLogin(formRef),
  1000,
  true
);

useEventListener(document, "keydown", ({ code }) => {
  if (
    ["Enter", "NumpadEnter"].includes(code) &&
    !disabled.value &&
    !loading.value
  )
    immediateDebounce(ruleFormRef.value);
});

watch(checked, bool => {
  userStore.SET_ISREMEMBERED(bool);
});
watch(loginDay, value => {
  userStore.SET_LOGINDAY(value);
});

watch(
  partialAction,
  action => {
    if (action === "need_bind_phone") {
      router.replace("/welcome/bindphone");
    } else if (action === "need_verify_identity") {
      router.replace("/welcome/verification");
    }
  },
  { immediate: true }
);
</script>

<template>
  <div class="select-none">
    <img :src="bg" class="wave" />
    <div class="flex-c absolute right-5 top-3">
      <el-switch
        v-model="dataTheme"
        inline-prompt
        :active-icon="dayIcon"
        :inactive-icon="darkIcon"
        @change="dataThemeChange"
      />
    </div>
    <div class="login-container">
      <div class="img">
        <component :is="toRaw(illustration)" />
      </div>
      <div class="login-box">
        <div class="login-form">
          <avatar class="avatar" />
          <Motion>
            <h2 class="outline-hidden">
              <TypeIt
                :options="{ strings: [title], cursor: false, speed: 100 }"
              />
            </h2>
          </Motion>

          <el-form
            v-if="currentPage === 0"
            ref="ruleFormRef"
            :model="ruleForm"
            :rules="loginRules"
            size="large"
          >
            <Motion :delay="100">
              <el-form-item prop="phone">
                <el-input
                  v-model="ruleForm.phone"
                  clearable
                  placeholder="请输入手机号"
                  :prefix-icon="useRenderIcon(User)"
                />
              </el-form-item>
            </Motion>

            <Motion :delay="150">
              <el-form-item prop="password">
                <el-input
                  v-model="ruleForm.password"
                  clearable
                  show-password
                  placeholder="请输入密码"
                  :prefix-icon="useRenderIcon(Lock)"
                />
              </el-form-item>
            </Motion>

            <Motion :delay="250">
              <el-form-item>
                <div class="w-full h-[20px] flex justify-between items-center">
                  <el-checkbox v-model="checked">
                    <span class="flex remember-wrap">
                      <select v-model="loginDay">
                        <option value="1">1</option>
                        <option value="7">7</option>
                        <option value="30">30</option>
                      </select>
                      记住登录
                      <el-tooltip :content="rememberTip" placement="top">
                        <span class="remember-tip">
                          <IconifyIconOffline icon="ep:info-filled" />
                        </span>
                      </el-tooltip>
                    </span>
                  </el-checkbox>
                  <el-button
                    link
                    type="primary"
                    @click="userStore.SET_CURRENTPAGE(4)"
                  >
                    忘记密码
                  </el-button>
                </div>
                <el-button
                  class="w-full mt-4!"
                  size="default"
                  type="primary"
                  :loading="loading"
                  :disabled="disabled"
                  @click="onLogin(ruleFormRef)"
                >
                  登录
                </el-button>
              </el-form-item>
            </Motion>

            <Motion :delay="300">
              <el-form-item>
                <div class="w-full h-[20px] flex justify-between items-center">
                  <el-button
                    v-for="item in operates"
                    :key="item.title"
                    class="w-full mt-4!"
                    size="default"
                    @click="userStore.SET_CURRENTPAGE(item.page)"
                  >
                    {{ item.title }}
                  </el-button>
                </div>
              </el-form-item>
            </Motion>
          </el-form>

          <!-- <Motion v-if="currentPage === 0" :delay="350">
            <el-form-item>
              <el-divider>
                <span class="divider-text">第三方登录</span>
              </el-divider>
              <div class="third-party">
                <span
                  v-for="item in thirdParty"
                  :key="item.title"
                  :title="item.title"
                >
                  <IconifyIconOnline
                    :icon="`ri:${item.icon}-fill`"
                    width="20"
                    class="cursor-pointer text-gray-500 hover:text-blue-400"
                  />
                </span>
              </div>
            </el-form-item>
          </Motion> -->

          <LoginPhone v-if="currentPage === 1" />
          <LoginQrCode v-if="currentPage === 2" />
          <LoginRegist v-if="currentPage === 3" />
          <LoginUpdate v-if="currentPage === 4" />
        </div>
      </div>
    </div>
    <div
      class="w-full flex-c absolute bottom-3 text-sm text-[rgba(0,0,0,0.6)] dark:text-[rgba(220,220,242,0.8)]"
    >
      Copyright © 2025-present
      <a
        class="hover:text-primary!"
        href="https://github.com/pure-admin"
        target="_blank"
      >
        &nbsp;{{ title }}
      </a>
    </div>
  </div>
</template>

<style scoped>
@import url("@/style/login.css");

.remember-wrap {
  align-items: center;
  gap: 4px;
}

.remember-wrap select {
  width: 24px;
  outline: none;
  background: transparent;
  border: none;
  appearance: none;
  text-align: center;
}

.remember-tip {
  font-size: 12px;
  color: #9ca3af;
  cursor: pointer;
}

.third-party {
  display: flex;
  justify-content: space-evenly;
  width: 100%;
  margin-top: 8px;
}

.divider-text {
  font-size: 12px;
  color: #9ca3af;
}
</style>
